<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2018/11/1
 * Time: 15:43
 */

namespace App\Weixin\Controllers\Home;

use App\Base\Controllers\Controller;
use App\FreeBird\Contracts\InfoClassInterface;
use App\FreeBird\Exceptions\FreeBirdException;
use App\Weixin\Contracts\UserInterface;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Aai\V20180522\AaiClient;
use TencentCloud\Aai\V20180522\Models\SentenceRecognitionRequest;


class UserController extends Controller
{
    /**
     * 获取用户接口
     * @return UserInterface
     */
    public function getUserInterface()
    {
        return app()->make(UserInterface::class);
    }


    /**
     * 获取分类接口
     * @return InfoClassInterface
     */
    public function getInfoClassInterface()
    {
        return app()->make(InfoClassInterface::class);
    }

    /**
     * 微信小程解密小程序用信息获取用户信息
     * @param Request $request
     * @return mixed
     */
    public function userLogin(Request $request)
    {
        //验证
        $validator = Validator::make($request->all(), [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ], ["code.required" => 'code参数是必须', "encryptedData.required" => 'encryptedData参数是必须', "iv.required" => 'iv参数是必须']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        return $this->getUserInterface()->wxXiaoUserLogin($request->all());
    }

    /**
     * 更新用户经纬度
     * @param Request $request
     */
    public function updateUserLngAndlat(Request $request)
    {

        //去掉金币与余额更新
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, $request->all());
    }

    /**
     * 修改用户头像
     * @param Request $request
     */
    public function userChangeInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'headimgurl' => 'required',
            'truename' => 'required',
            'qqcode' => 'required',
            'wxcode' => 'required',
            //'istrue'=>'required',
        ], ["headimgurl.required" => '头像参数不能为空', "truename.required" => '真实姓名参数不能为空', "qqcode.required" => 'QQ二维码参数不能为空', "wxcode.required" => '微信二维码参数不能为空']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, $request->except(['istrue', 'token']));
    }

    public function userChangeLoginInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            // 'headimgurl' => 'required',
            'truename' => 'required',
            'qqcode' => 'required',
            'wxcode' => 'required',
            'istrue' => 'required',
        ], ["truename.required" => '真实姓名参数不能为空', "qqcode.required" => 'QQ二维码参数不能为空', "wxcode.required" => '微信二维码参数不能为空', "istrue.required" => '是否选中参数不能为空']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, $request->except(['istrue', 'token']));
    }

    public function userChangeSet(Request $request)
    {
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, $request->except(['istrue', 'token']));
    }

    /**
     * 用户更新头像
     * @param Request $request
     * @return mixed
     * @throws \App\Base\Exceptions\ApiException
     */

    public function userChangeUsername(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'truename' => 'required',
        ], ["truename.required" => '头像参数不能为空']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, $request->all());
    }


    /**
     *上传音频换文字
     * @param Request $request
     */
    public function wxVedio(Request $request)
    {

        $file = $request->file("viceo");
        $realPath = $file->getRealPath();
        $ext = $file->getClientOriginalExtension();
        $md5 = md5_file($realPath);     //图片md5
        $sha1 = sha1_file($realPath);
        // 上传文件
        $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
        // 使用我们新建的uploads本地存储空间（目录）
        $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
        if ($bool) {
            $url = URL::current();
            try {
                $cred = new Credential("AKIDWqvlKeSY9WfaHjo5tSqzsVt1tWyGtP6Y", "LSJuQggU8XifOs89wUmqfEXaOxGK8i39");
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint("aai.tencentcloudapi.com");
                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile($httpProfile);
                $client = new AaiClient($cred, "ap-guangzhou", $clientProfile);
                $req = new SentenceRecognitionRequest();
                $params = '{
            "ProjectId":"0"
            ,"SubServiceType":"2"
            ,"EngSerViceType":"16k"
            ,"SourceType":"0"
            ,"VoiceFormat":"mp3"
            ,"UsrAudioKey":"' . time() . '"
            ,"Url":' . $url . '"/uploads/' . $filename . '"      
            }';
                $req->fromJsonString($params);
                $resp = $client->SentenceRecognition($req);
                Storage::disk('uploads')->delete($filename);
                return json_decode($resp->toJsonString(), true);
            } catch (TencentCloudSDKException $e) {
                echo $e;
                exit;
            }
        } else {

        }
    }


    public function Test()
    {
        try {
            $cred = new Credential("AKIDWqvlKeSY9WfaHjo5tSqzsVt1tWyGtP6Y", "LSJuQggU8XifOs89wUmqfEXaOxGK8i39");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("aai.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new AaiClient($cred, "ap-guangzhou", $clientProfile);
            $req = new SentenceRecognitionRequest();
            $params = '{
            "ProjectId":"0"
            ,"SubServiceType":"2"
            ,"EngSerViceType":"16k"
            ,"SourceType":"0"
            ,"VoiceFormat":"mp3"
            ,"UsrAudioKey":"' . time() . '"
            "Url":"http://120.78.218.116/uploads/2018-11-07-09-41-12-5be2b3386f50d.mp3"      
            }';
            $req->fromJsonString($params);
            $resp = $client->SentenceRecognition($req);

            print_r($resp->toJsonString());
            exit;
        } catch (TencentCloudSDKException $e) {
            throw  new \Exception($e->getMessage());
        }
    }

    /**
     * 余额信息列表
     * @param Request $request
     * @return mixed
     */
    public function getBalanceLogList(Request $request)
    {
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->getBalanceLogList($where);
    }

    /**
     * 获取入驻用户列表
     * @param Request $request
     */
    public function lidList(Request $request)
    {

        $where = function ($query) use ($request) {
            $keyword = $request->input("keyword");
            if (!empty($keyword)) {
                $query->where("class_name", "like", '%' . $keyword . '%');  //行业搜索
                $query->where("nickname", "like", '%' . $keyword . '%');  //昵称搜索
                $query->where("truename", "like", '%' . $keyword . '%');  //真实姓名搜索
            }
            $query->whereNotNull("longitude");  //经度不为空
            $query->whereNotNull("latitude");  //纬度不为空
            $query->whereNotNull("class");  //分类不为空
            $query->where("lid", 2);
        };
        $userList = $this->getUserInterface()->getUserList($where);  //获取用户列表
        $userListArr = $userList->toArray();
        foreach ($userListArr as $k => $v) {
            if ((time() - 1800) < $v['update_time']) { //30分钟那么用户在线
                $userListArr[$k]['is_online'] = 1;
                $userListArr[$k]['is_online_logo'] = get_config_param_value("WX_ONLINE_ICON");
            } else {
                $userListArr[$k]['is_online'] = 0;
                $userListArr[$k]['is_online_logo'] = get_config_param_value("WX_NOT_ONLINE_ICON");
            }
        }
        return $userListArr;
    }

    public function classList(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required',
        ], ["class_id.required" => '分类id不能为空']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        $classId = $request->input("class_id");
        $where = function ($query) use ($classId) {
            $query->where("class", $classId);  //分类id;
            $query->where("lid", 2);
        };
        $userList = $this->getUserInterface()->getUserList($where);  //获取用户列表
        $userListArr = $userList->toArray();
        //获取分类id图标
        $classInfo = $this->getInfoClassInterface()->getInfo(["id" => $classId]);
        if (empty($classInfo)) {
            throw  new  FreeBirdException(FreeBirdException::EROOR_REDPAKE_CATEGROY_ERROR);
        }
        $classIcon = $classInfo->logo;
        foreach ($userListArr as $k => $v) {
            $userListArr[$k]['is_online'] = 0;
            $userListArr[$k]['is_online_logo'] = $classIcon;
//            if((time()-1800)<$v['update_time']){ //30分钟那么用户在线
//                $userListArr[$k]['is_online']=1;
//                $userListArr[$k]['is_online_logo']=$classIcon;
//            }else{
//                $userListArr[$k]['is_online']=0;
//                $userListArr[$k]['is_online_logo']=get_config_param_value("WX_NOT_ONLINE_ICON");
//            }
        }
        return $userListArr;

    }


    /**
     * 入驻用户信息
     * @param Request $request
     */
    public function indexInfo(Request $request)
    {
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->getUserInfoByIdLib($where);
    }


    /**
     * 获取用户详细信息含评论
     * @param Request $request
     * @return mixed
     */
    public function getDetail(Request $request)
    {
        $where = function ($query) {

        };
        return $this->getUserInterface()->getDetail($where);
    }

    /**
     * 用户类型
     * @param Request $request
     */
    public function changUserType(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_type' => 'required',
        ], ["user_type.required" => '分类id不能为空']);
        if ($validator->fails()) {
            $this->throwValidatorException($validator);
        }
        $userType = $request->input("user_type");
        $where = function ($query) {
            $query->where("uid", AUID);
        };
        return $this->getUserInterface()->updateXiaoUserInfo($where, ["user_type" => $userType]);
    }


    /**
     * 用户统计
     * @param Request $request
     */
    public function infoStatistics(Request $request)
    {
        return $this->getUserInterface()->getInfoStatistics($request->except("token"));
    }




    public function testWx(Request $request)
    {

        return $this->getUserInterface()->testWx($request->all());
    }


}